package com.zhyonk.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.NumberUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhyonk.config.propreties.BaiduProperties;
import com.zhyonk.domain.StarUser;
import com.zhyonk.mapper.StarUserMapper;
import com.zhyonk.service.AsyncService;
import com.zhyonk.service.FaceService;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;

import java.util.*;

@Service("faceService")
public class FaceServiceImpl implements FaceService {

    @Autowired
    private BaiduProperties baiduProperties;

    @Autowired
    private StarUserMapper starUserMapper;

    @Autowired
    private AsyncService asyncService;


    @Override
    public void payFor(String someThings) {
        System.out.println("Ok,Now pay " + someThings);
    }

    @Override
    public JSONObject checkFace(HashMap<String, String> options, String image, String imageType) {
        return baiduProperties.getAipFaceClient().detect(image,imageType,options);
    }

    @Override
    public JSONObject searchFace(HashMap<String, String> options, String image, String imageType, String groupIdList) {
        return baiduProperties.getAipFaceClient().search(image,imageType,groupIdList,options);
    }

    @Override
    public JSONObject multiSearchFace(HashMap<String, String> options, String image, String imageType, String groupIdList) {
        return baiduProperties.getAipFaceClient().multiSearch(image,imageType,groupIdList,options);
    }

    @Override
    public JSONObject addUser(HashMap<String, String> options, String image, String imageType, String groupId, String userId) {
        return baiduProperties.getAipFaceClient().addUser(image,imageType,groupId,userId,options);
    }

    @Override
    public JSONObject colourize(String base64) {
        base64 = base64.replace("data:image/png;base64,","");
        return baiduProperties.getAipImageProcessClient().colourize(Base64Utils.decodeFromString(base64), new HashMap<>());
    }

    @Override
    public StarUser queryStarFace(String base64) {
        base64 = base64.replace("data:image/png;base64,","");
        ArrayList<StarUser> starList = getStarList(base64);
        if (Objects.isNull(starList)) {
            return null;
        }
        if (starList.isEmpty()){
            return null;
        }
        return starList.get(0);
    }

    @Override
    public Map<String, Object> fillFieldEntity(Object obj, HashMap<String, String> needFields) {
        Map<String, Object> bean = BeanUtil.beanToMap(obj);
        HashMap<String, Object> result = new HashMap<>();
        for (String item : bean.keySet()){
            if (needFields.containsKey(item)){
                result.put(needFields.get(item),bean.get(item));
            }
        }
        return result;
    }

    private ArrayList<StarUser> getStarList(String base64) {
        HashMap<String, String> option = new HashMap<>();
        option.put("max_user_num", "3");
        JSONObject jsonObject = searchFace(option, base64, "BASE64", "star");

        if (jsonObject.getInt("error_code") != 0) {
            System.out.println(jsonObject.getString("error_msg"));
            return null;
        }
        JSONArray jsonArray = jsonObject.getJSONObject("result").getJSONArray("user_list");

        ArrayList<StarUser> starList = new ArrayList<>();

        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject item = jsonArray.getJSONObject(i);
            long userId = item.getLong("user_id");
            StarUser user = starUserMapper.selectById(userId);
            double score = item.getDouble("score");
            user.setScoure(NumberUtil.decimalFormat("0.00", score));
            starList.add(user);
        }
        return starList;
    }


    @Override
    public void fillUser() {
        //查出整个用户列表
//        List<StarUser> userList = userMapper.selectList(new QueryWrapper<>());
        StarUser selectById = starUserMapper.selectById(112495);
        List<StarUser> userList =new ArrayList<>();
        userList.add(selectById);
        //遍历
        for (StarUser user : userList){
            try{
                asyncService.execSetUserOption(user);
            }catch (Exception e){
                e.printStackTrace();
            }
            System.out.println("开始： "+user.getId() + ":" + user.getName() + "已经放到线程池中");
        }
    }

    @Override
    public void registerAllUserToBaidu() {
        QueryWrapper<StarUser> wrapper = new QueryWrapper<>();
        wrapper.isNull("face_token");
        //查出整个用户列表
//        List<StarUser> userList = userMapper.selectList(wrapper);

        StarUser selectById = starUserMapper.selectById(112495);
        List<StarUser> userList =new ArrayList<>();
        userList.add(selectById);

        int count = 0;
        //遍历
        for (StarUser user : userList){
            try{
                asyncService.execPushInfoToBaidu(user);
            }catch (Exception e){
                e.printStackTrace();
            }
            System.out.println("开始： "+user.getId() + ":" + user.getName() + "已经放到线程池中");
            count ++;
            if (count == 10){
                try {
                    Thread.sleep(1500);
                    count = 0;
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public void deleteFace() {
        HashMap<String, String> map = new HashMap<>();
        map.put("length","1000");
        for (int i = 0; i <= 10 ; i++) {
            map.put("start",i*1000 +"");
            JSONObject star = baiduProperties.getAipFaceClient().getGroupUsers("star", map);
            JSONArray userIdList = star.getJSONObject("result").getJSONArray("user_id_list");
            int count = 0;
            for (int j = 0 ; j < userIdList.length(); j++) {
                try{
                    baiduProperties.getAipFaceClient().deleteUser("star",userIdList.getString(j),map);
                }catch (Exception e){
                    e.printStackTrace();
                }
                count ++;
                if (count == 10){
                    try {
                        Thread.sleep(1000);
                        count = 0;
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    @Override
    public int containFaceCount(String base64) {
        HashMap<String, String> option = new HashMap<>();
        JSONObject jsonObject = baiduProperties.getAipFaceClient().detect(base64, "BASE64", option);
        int error_code = jsonObject.getInt("error_code");
        if (error_code == 222202){
            return 0;
        }
        return jsonObject.getJSONObject("result").getInt("face_num");
    }
}
